#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试 ChromaDBClient.search_documents 方法
分析为什么搜索返回空结果
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.config import load_config
from src.database.chromadb_client import ChromaDBClient
import chromadb

async def debug_search_documents():
    """调试搜索文档方法"""
    print("=== 调试 ChromaDBClient.search_documents 方法 ===")
    
    try:
        # 1. 加载配置
        print("\n1. 加载配置...")
        config = load_config()
        chromadb_config = config.get('chromadb', {})
        print(f"ChromaDB配置: {chromadb_config}")
        
        # 2. 直接连接 ChromaDB
        print("\n2. 直接连接 ChromaDB...")
        data_dir = chromadb_config.get('data_dir', './data/chromadb')
        client = chromadb.PersistentClient(path=data_dir)
        
        # 3. 检查 conversations 集合
        print("\n3. 检查 conversations 集合...")
        try:
            conversations_collection = client.get_collection("conversations")
            count = conversations_collection.count()
            print(f"✅ conversations 集合存在，包含 {count} 个文档")
            
            # 获取所有文档查看结构
            if count > 0:
                all_docs = conversations_collection.get(limit=3, include=['documents', 'metadatas'])
                print(f"\n示例文档:")
                for i, (doc, meta) in enumerate(zip(all_docs['documents'], all_docs['metadatas'])):
                    print(f"  文档 {i+1}:")
                    print(f"    内容: {doc[:50]}...")
                    print(f"    元数据: {meta}")
                    print(f"    用户ID: {meta.get('user_id')}")
                    
        except Exception as e:
            print(f"❌ conversations 集合不存在: {e}")
            return
        
        # 4. 初始化 ChromaDBClient
        print("\n4. 初始化 ChromaDBClient...")
        chromadb_client = ChromaDBClient(config)
        await chromadb_client.connect()
        
        # 5. 测试不同的搜索参数
        print("\n5. 测试搜索参数...")
        
        test_cases = [
            {
                'name': '无过滤条件搜索',
                'query': '王者荣耀',
                'where': None,
                'n_results': 5
            },
            {
                'name': '带用户ID过滤搜索',
                'query': '王者荣耀',
                'where': {'user_id': 'default_user'},
                'n_results': 5
            },
            {
                'name': '搜索游戏关键词',
                'query': '游戏',
                'where': {'user_id': 'default_user'},
                'n_results': 3
            },
            {
                'name': '搜索英雄关键词',
                'query': '英雄',
                'where': None,
                'n_results': 3
            }
        ]
        
        for test_case in test_cases:
            print(f"\n5.{test_cases.index(test_case)+1} {test_case['name']}")
            print(f"    查询: '{test_case['query']}'")
            print(f"    过滤条件: {test_case['where']}")
            print(f"    结果数量: {test_case['n_results']}")
            
            try:
                # 调用 ChromaDBClient 的 search_documents 方法
                results = await chromadb_client.search_documents(
                    'conversations',
                    test_case['query'],
                    n_results=test_case['n_results'],
                    where=test_case['where']
                )
                
                print(f"    结果: {len(results.get('documents', []))} 条")
                if results.get('documents'):
                    print(f"    示例内容: {results['documents'][0][:50]}...")
                    print(f"    示例元数据: {results['metadatas'][0] if results.get('metadatas') else 'None'}")
                    print(f"    相似度: {1 - results['distances'][0] if results.get('distances') else 'None'}")
                else:
                    print(f"    ❌ 未找到结果")
                    
                    # 如果有过滤条件但没找到结果，尝试无过滤搜索
                    if test_case['where']:
                        print(f"    尝试无过滤搜索...")
                        fallback_results = await chromadb_client.search_documents(
                            'conversations',
                            test_case['query'],
                            n_results=test_case['n_results'],
                            where=None
                        )
                        print(f"    无过滤结果: {len(fallback_results.get('documents', []))} 条")
                        
            except Exception as e:
                print(f"    ❌ 搜索失败: {e}")
                import traceback
                traceback.print_exc()
        
        # 6. 测试直接 ChromaDB 查询对比
        print("\n6. 直接 ChromaDB 查询对比...")
        try:
            # 直接使用 ChromaDB 客户端搜索
            direct_results = conversations_collection.query(
                query_texts=["王者荣耀"],
                n_results=5,
                where={'user_id': 'default_user'},
                include=['documents', 'metadatas', 'distances']
            )
            
            print(f"直接查询结果: {len(direct_results['documents'][0])} 条")
            if direct_results['documents'][0]:
                print(f"示例: {direct_results['documents'][0][0][:50]}...")
                print(f"元数据: {direct_results['metadatas'][0][0]}")
            
        except Exception as e:
            print(f"❌ 直接查询失败: {e}")
        
        # 7. 检查嵌入生成
        print("\n7. 检查嵌入生成...")
        try:
            embedding = await chromadb_client.generate_embeddings("王者荣耀")
            print(f"嵌入向量长度: {len(embedding)}")
            print(f"嵌入向量前5个值: {embedding[:5]}")
        except Exception as e:
            print(f"❌ 嵌入生成失败: {e}")
        
        # 8. 清理
        await chromadb_client.close()
        print("\n✅ 调试完成")
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(debug_search_documents())